package com.example.sharding.repository;


import cn.hutool.core.lang.Snowflake;
import com.example.sharding.entity.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;

@Repository
public class OrderRepository {

    private final JdbcTemplate jdbcTemplate;

    @Autowired
    private Snowflake idGenerator;

    public OrderRepository(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    public void save(Order order) {
        String sql = "INSERT INTO t_order (order_id, user_id, amount, create_time) VALUES (?, ?, ?, ?)";
        jdbcTemplate.update(sql, idGenerator.nextId(), order.getUserId(), order.getAmount(), order.getCreateTime());
    }

    public List<Order> findByUserId(Integer userId) {
        String sql = "SELECT * FROM t_order WHERE user_id = ?";
        return jdbcTemplate.query(sql, new OrderRowMapper(), userId);
    }

    public List<Order> findByCreateTimeBetween(Date start, Date end) {
        String sql = "SELECT * FROM t_order WHERE create_time BETWEEN ? AND ?";
        return jdbcTemplate.query(sql, new OrderRowMapper(), start, end);
    }

    private static class OrderRowMapper implements RowMapper<Order> {
        @Override
        public Order mapRow(ResultSet rs, int rowNum) throws SQLException {
            Order order = new Order();
            order.setOrderId(rs.getLong("order_id"));
            order.setUserId(rs.getInt("user_id"));
            order.setAmount(rs.getBigDecimal("amount"));
            order.setCreateTime(rs.getTimestamp("create_time"));
            return order;
        }
    }
}
